<template>
  <div class="app-container">
    <!-- 搜索和操作区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form" @submit.native.prevent>
        <el-form-item label="课程名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入课程名称"
            clearable
            size="small"
            @keyup.enter.native="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button size="small" icon="el-icon-search" type="primary" @click="handleSearch">搜索</el-button>
          <el-button size="small" @click="resetSearch" icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格区域 -->
    <div class="content-container">
      <div class="content-header">
        <span class="title">课程列表</span>
        <div class="action-buttons-container">
          <el-button type="primary" size="small" @click="dialogFormVisible = true; course={}" icon="el-icon-plus">新增课程</el-button>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        v-loading="loading"
        highlight-current-row
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border
        :header-cell-style="{background:'#fafafa',color:'#606266',fontWeight: 'bold'}"
        stripe
        empty-text="暂无课程数据"
      >
        <el-table-column type="index" width="100" label="序号" align="center" :index="calculateIndex" />
        <el-table-column prop="name" label="课程名称" align="center" />
        <el-table-column prop="description" label="课程描述" align="center" />
        <el-table-column label="最后操作时间" align="center">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.updateTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="420" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="selectById(scope.row.id)"
            >编辑</el-button>

            <el-button
              size="mini"
              type="danger"
              @click="deleteById(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        background
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新建/编辑对话框 -->
    <el-dialog title="保存课程" :visible.sync="dialogFormVisible" width="500px">
      <el-form :model="course" ref="courseForm" :rules="courseRules">
        <el-form-item label="课程名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="course.name" placeholder="请输入课程名称" autocomplete="off" />
        </el-form-item>
        <el-form-item label="课程描述" :label-width="formLabelWidth" prop="description">
          <el-input v-model="course.description" placeholder="请输入课程描述" autocomplete="off" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="add()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { page, add, update, deleteById, selectById } from '@/api/course.js'

export default {
  data() {
    return {
      formLabelWidth: '120px',
      dialogFormVisible: false, // 控制对话框是否可见
      course: {
        name: '',
        description: ''
      },
      tableData: [],
      searchForm: {
        name: ''
      },
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      courseRules: {
        name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入课程描述', trigger: 'blur' },
          { min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    // 当页面加载完成后自动执行。
    this.init()
  },

  methods: {

    // 删除课程
    deleteById(id) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById(id).then((result) => {
          if (result.data.code === 1) {
            this.$message({
              message: '恭喜你，删除成功',
              type: 'success'
            })
          } else {
            this.$message.error(result.data.msg)
          }
          // 重新查询数据
          this.init()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 根据ID查询课程 -- 回显
    selectById(id) {
      this.dialogFormVisible = true
      selectById(id).then((result) => {
        this.course = result.data.data
      })
    },

    // 保存方法
    add() {
      this.$refs.courseForm.validate((valid) => {
        if (valid) {
          let method // 添加
          if (this.course.id) {
            method = update(this.course) // 修改
          } else {
            method = add(this.course) // 添加
          }
          method.then((result) => {
            if (result.data.code === 1) {
              // 修改成功
              this.$message.success('恭喜你，保存成功')
              // 重新查询数据
              this.init()
            } else {
              this.$message.error(result.data.msg)
            }
          })
          // 关闭新建窗口
          this.dialogFormVisible = false

          // 清空模型数据
          this.course = {}
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 初始化 - 查询全部
    init() {
      this.loading = true
      const params = {
        name: this.searchForm.name, // 搜索的课程名称
        page: this.currentPage, // 当前页码，对应后端 page 参数
        size: this.pageSize // 每页大小，对应后端 size 参数
      }
      page(params).then((result) => {
        this.tableData = result.data.data.records
        this.total = result.data.data.total
        this.loading = false
      })
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.init()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm.name = ''
      this.currentPage = 1
      this.init()
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pageSize = val
      this.init()
    },

    // 当前页码变化
    handleCurrentChange(val) {
      this.currentPage = val
      this.init()
    },

    // 计算序号
    calculateIndex(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      return date.toLocaleString()
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.search-container {
  margin-bottom: 20px;
}
.search-form {
  padding: 20px;
  background: #f9f9f9;
  border-radius: 6px;
}
.content-container {
  background: #fff;
  padding: 20px;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}
.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}
.title {
  font-size: 18px;
  font-weight: bold;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
